package com.meepo.sdk.utils.store

import android.app.ActivityManager
import android.content.Context
import android.os.Build
import android.os.Environment
import androidx.annotation.RequiresApi
import com.meepo.sdk.utils.Utils
import com.meepo.sdk.utils.UtilsBridge
import java.io.File
import java.math.BigDecimal

class CacheDirUtils private constructor() {

    companion object {

        /**
         * 获取缓存大小
         * @param context
         * @return
         * @throws Exception
         */
        @Throws(Exception::class)
        fun getTotalCacheSize(): String {
            var cacheSize = getFolderSize(Utils.getApp().cacheDir)
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                cacheSize += getFolderSize(Utils.getApp().externalCacheDir)
            }
            return getFormatSize(cacheSize.toDouble())
        }

        /***
         * 清理所有缓存
         * @param context
         */
        fun clearAllCache(context: Context) {
            deleteDir(context.cacheDir)
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                deleteDir(context.externalCacheDir)
            }
        }

        private fun deleteDir(dir: File?): Boolean {
            if (dir != null && dir.isDirectory) {
                dir.list()?.let {
                    for (i in it.indices) {
                        val success =
                            deleteDir(File(dir, it[i]))
                        if (!success) {
                            return false
                        }
                    }
                }

            }
            return dir!!.delete()
        }

        // 获取文件
        //Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
        //Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
        @Throws(Exception::class)
        fun getFolderSize(file: File?): Long {
            var size: Long = 0
            try {
                val fileList = file!!.listFiles()
                for (i in fileList.indices) {
                    // 如果下面还有文件
                    size = if (fileList[i].isDirectory) {
                        size + getFolderSize(fileList[i])
                    } else {
                        size + fileList[i].length()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return size
        }

        /**
         * 格式化单位
         *
         * @param size
         * @return
         */
        fun getFormatSize(size: Double): String {
            val kiloByte = size / 1024
            if (kiloByte < 1) {
//            return size + "Byte";
                return "0K"
            }
            val megaByte = kiloByte / 1024
            if (megaByte < 1) {
                val result1 =
                    BigDecimal(java.lang.Double.toString(kiloByte))
                return result1.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB"
            }
            val gigaByte = megaByte / 1024
            if (gigaByte < 1) {
                val result2 =
                    BigDecimal(java.lang.Double.toString(megaByte))
                return result2.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB"
            }
            val teraBytes = gigaByte / 1024
            if (teraBytes < 1) {
                val result3 =
                    BigDecimal(java.lang.Double.toString(gigaByte))
                return result3.setScale(2, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB"
            }
            val result4 = BigDecimal(teraBytes)
            return (result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()
                    + "TB")
        }

        /**
         * Clean the internal cache.
         *
         * directory: /data/data/package/cache
         *
         * @return `true`: success<br></br>`false`: fail
         */
        fun cleanInternalCache(): Boolean {
            return UtilsBridge.deleteAllInDir(Utils.getApp().cacheDir)
        }

        /**
         * Clean the internal files.
         *
         * directory: /data/data/package/files
         *
         * @return `true`: success<br></br>`false`: fail
         */
        fun cleanInternalFiles(): Boolean {
            return UtilsBridge.deleteAllInDir(Utils.getApp().filesDir)
        }

        /**
         * Clean the internal databases.
         *
         * directory: /data/data/package/databases
         *
         * @return `true`: success<br></br>`false`: fail
         */
        fun cleanInternalDbs(): Boolean {
            return UtilsBridge.deleteAllInDir(File(Utils.getApp().filesDir.parent, "databases"))
        }

        /**
         * Clean the internal database by name.
         *
         * directory: /data/data/package/databases/dbName
         *
         * @param dbName The name of database.
         * @return `true`: success<br></br>`false`: fail
         */
        fun cleanInternalDbByName(dbName: String?): Boolean {
            return Utils.getApp().deleteDatabase(dbName)
        }

        /**
         * Clean the internal shared preferences.
         *
         * directory: /data/data/package/shared_prefs
         *
         * @return `true`: success<br></br>`false`: fail
         */
        fun cleanInternalSp(): Boolean {
            return UtilsBridge.deleteAllInDir(File(Utils.getApp().filesDir.parent, "shared_prefs"))
        }

        /**
         * Clean the external cache.
         *
         * directory: /storage/emulated/0/android/data/package/cache
         *
         * @return `true`: success<br></br>`false`: fail
         */
        fun cleanExternalCache(): Boolean {
            return Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() && UtilsBridge.deleteAllInDir(Utils.getApp().externalCacheDir)
        }

        /**
         * Clean the custom directory.
         *
         * @param dirPath The path of directory.
         * @return `true`: success<br></br>`false`: fail
         */
        fun cleanCustomDir(dirPath: String?): Boolean {
            return UtilsBridge.deleteAllInDir(UtilsBridge.getFileByPath(dirPath))
        }

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        fun cleanAppUserData() {
            val am = Utils.getApp().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            am.clearApplicationUserData()
        }
    }
}